package com.yami.shop.api.controller;

import cn.hutool.json.JSONObject;
import com.google.gson.Gson;
import com.yami.shop.bean.model.AccessToken;
import com.yami.shop.common.util.SpringContextUtils;
import io.micrometer.core.instrument.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.client.RestTemplate;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.TimeUnit;

public class SendMessageToUser {
    private static RedisTemplate<String,Object> redisTemplate = SpringContextUtils.getBean("redisTemplate",RedisTemplate.class);
    @Autowired
    private RestTemplate restTemplate;
    /**
     * @Description: 获取access_token
     * @author: cjm
     * @date: 2020/06/03
     * @param: [appid, appsecret]
     * @return: java.lang.String
     */
    public String getToken(String appid, String appsecret){
        // 先判断redis中是否存在
        String user ="messageToken";
        String token = (String)redisTemplate.opsForValue().get(user);
        if (StringUtils.isBlank(token) == false) {
            // token还未过期，获取后直接返回，无需重新获取
            return token;
        }
        //  token已过期或不存在，需重新获取
        redisTemplate.delete("messageToken");

        //获取access_token
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
                "&appid=" + appid + "&secret=" + appsecret;
        String json = restTemplate.getForObject(url, String.class);
        AccessToken accessToken = new Gson().fromJson(json, AccessToken.class);
        if(accessToken!=null) {
            redisTemplate.opsForValue().set("messageToken", accessToken, Integer.valueOf(accessToken.getExpires_in()) - 60, TimeUnit.SECONDS);
        }
        return accessToken.getAccess_token();
    }



}
